<template>
	<el-container>
		<el-aside width="100%" v-loading="showDicloading">
			<el-container>
				<el-header v-if="searchHide">
					<el-input placeholder="搜索请输入关键字" v-model="dicFilterText" clearable />
				</el-header>
				<el-main class="nopadding">
					<el-tree ref="dicRef" :current-node-key="''" :default-expand-all="true" class="menu" node-key="id"
						:data="dicList" :props="dicProps" :highlight-current="true" :expand-on-click-node="false"
						:filter-node-method="dicFilterNode" @node-click="dicClick">
						<template #default="{ data }">
							<span class="custom-tree-node">
								<span class="cat_name">{{ data.cat_name }}</span>
								<template v-if="!data.id && !hideDo">
									<el-button-group v-if="data.id===''">
										<el-button size="small" type="primary" icon="Plus"
											@click.stop="dicPlus(data)" />
									</el-button-group>
								</template>
								<span class="do" v-else-if="!hideDo">
									<el-button-group v-if="false">
										<el-button size="small" type="primary" icon="Plus"
											@click.stop="dicPlus(data)" />
										<el-button size="small" type="primary" icon="Edit"
											@click.stop="dicEdit(data)" />
										<el-button size="small" type="danger" icon="Delete"
											@click.stop="dicDel(data)" />
									</el-button-group>

									<el-button-group>
										<el-button size="small" icon="Plus" @click.stop="dicPlus(data)" />
										<el-dropdown trigger="click">
											<el-button size="small" icon="ArrowDown" @click.stop="" />
											<template #dropdown>
												<el-dropdown-menu>
													<el-dropdown-item>
														<el-button size="small" type="primary" icon="Edit"
															@click.stop="dicEdit(data)">
															编辑
														</el-button>
													</el-dropdown-item>
													<el-dropdown-item>
														<el-button size="small" type="danger" icon="Delete"
															@click.stop="dicDel(data)">
															删除
														</el-button>
													</el-dropdown-item>
												</el-dropdown-menu>
											</template>
										</el-dropdown>
									</el-button-group>


								</span>
							</span>
						</template>
					</el-tree>
				</el-main>

				<el-footer style="height:51px;">
					<el-button type="primary" size="small" icon="el-icon-plus" style="width: 100%;"
						@click="dicPlus({id:''})">
						{{title}}
					</el-button>
				</el-footer>
			</el-container>
		</el-aside>
	</el-container>

	<el-dialog title="新增类目" v-model="visible" :width="500" destroy-on-close @closed="$emit('closed')">
		<el-form :model="form" :rules="rules" ref="dialogForm" label-width="100px">
			<el-form-item label="上级类目" prop="parent_id">
				<el-cascader v-model="form.parent_id" :options="nowDicList" :props='{value: "id", label: "cat_name" ,
					emitPath: false, checkStrictly: true }' :show-all-levels="true" clearable style="width: 100%;"></el-cascader>
			</el-form-item>
			<el-form-item label="类目名称" prop="cat_name">
				<el-input v-model="form.cat_name" placeholder="类目名称" clearable></el-input>
			</el-form-item>
			<el-form-item label="排序" prop="sort">
				<el-input-number v-model="form.order" controls-position="right" :min="1"
					style="width: 100%;"></el-input-number>
			</el-form-item>
			<el-form-item label="是否有效" prop="status">
				<el-switch v-model="form.status" :active-value="1" :inactive-value="0"></el-switch>
			</el-form-item>
			<el-form-item label="备注" prop="remark">
				<el-input v-model="form.remark" clearable type="textarea"></el-input>
			</el-form-item>
		</el-form>
		<template #footer>
			<el-button @click="visible=false">取 消</el-button>
			<el-button type="primary" :loading="isSaveing" @click="submit()">保 存</el-button>
		</template>
	</el-dialog>


</template>

<script setup>
	/**
	 * @name scTree
	 * @desc 系统page左侧树状组件
	 * @prop {Funciton} apiObj - 请求树状参数接口
	 * @prop {Boolean} [searchHide=true] - 是否隐藏搜索框（默认不隐藏）
	 * @emits update:count - 当计数器变化时触发的事件
	 * @example
	 * <ComponentName title="Demo" :count="5" @update:count="handleUpdate" />
	 */
	import {
		ref,
		watch,
		onMounted,
		getCurrentInstance
	} from 'vue'
	const {
		proxy
	} = getCurrentInstance();

	const props = defineProps({
		apiUrl: {
			type: String,
			default: "system/category/manage",
		},
		apiObj: {
			type: Object,
			default: () => ({})
		},
		searchHide: {
			type: Boolean,
			default: true
		},
		title: {
			type: String,
			default: "",
		},
		model: {
			type: String,
			default: "",
		},
		hideDo: {
			type: Boolean,
			default: false
		}
	})

	const emit = defineEmits(['node-click', 'dicPlus'])

	// data
	const showDicloading = ref(true)
	const dicList = ref([])
	const nowDicList = ref([])
	const mode = ref('add')
	const dicFilterText = ref('')
	const dicProps = ref({
		label: 'cat_name'
	})
	const dicRef = ref(null)

	const visible = ref(false)
	const form = ref({
		id: "",
		parent_id: "",
		label: "",
		cat_name: "",
		order: 200,
		status: 1,
		cat_icon: "",
		model: "",
		remark: ""
	})
	const rules = ref({
		cat_name: [{
			required: true,
			message: '类名称必填'
		}],
		order: [{
			required: true,
			message: '请输入排序',
			trigger: 'change'
		}]
	})
	const isSaveing = ref(false)

	// 方法
	const submit = () => {

		form.value.model = proxy.model;

		proxy.$refs.dialogForm.validate(async (valid) => {
			if (valid) {
				isSaveing.value = true;
				var res;
				if (mode.value == 'add') {
					res = await proxy.$API.system.commPost(props.apiUrl + "/create")(form.value);
				} else {
					res = await proxy.$API.system.commPost(props.apiUrl + "/update")(form.value);
				}
				isSaveing.value = false;
				if (res.code == 0) {
					getDic();
					visible.value = false;
					proxy.$message.success("操作成功")
				} else {
					proxy.$alert(res.message, "提示", {
						type: 'error'
					})
				}
			}
		})
	}

	const getDic = async () => {
		try {
			const res = await proxy.$API.system.commPost(props.apiUrl + "/tree")({
				model: proxy.model
			})
			const allNode = [{
				id: null,
				cat_name: proxy.title,
			}, {
				id: '',
				cat_name: "全部",
				children: res.data
			}]

			if (proxy.title && false) {
				dicList.value = allNode
			} else {
				dicList.value = [allNode[1]]
			}

		} finally {
			showDicloading.value = false
		}
	}

	const initForm = () => {
		form.value = {
			id: "",
			parent_id: "",
			label: "",
			cat_icon: "",
			cat_name: "",
			order: 200,
			status: 1,
			remark: ""
		};
	}

	const getCurrentNode = () => {
		return proxy.$refs.dicRef.getCurrentNode();
	}

	const dicFilterNode = (value, data) => {
		if (!value) return true
		const targetText = data.key + data.cat_name
		return targetText.includes(value)
	}

	const dicPlus = (data) => {
		initForm();
		mode.value = 'add';
		visible.value = true;
		if (data.id) {
			form.value.parent_id = data.id;
		}
	}

	const dicEdit = (data) => {
		mode.value = 'edit';
		visible.value = true;
		form.value = data
	}

	const dicClick = (data) => {
		emit('node-click', data)
	}

	const dicDel = (data) => {
		ElMessageBox.confirm(
			`确定删除 ${data.cat_name} 项吗？`,
			'提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}
		).then(() => {

			proxy.$API.system.commPost(props.apiUrl + "/remove")({
				id: data.id,
				model: proxy.model
			}).then(res => {
				if (res.code == 0) {
					proxy.$message.success("删除成功")
				} else {
					proxy.$alert(res.message, "提示", {
						type: 'error'
					})
				}
				getDic();
			})

		}).catch(() => {})
	}

	// 生命周期
	onMounted(() => {
		getDic()
	})

	// 观察器
	watch(dicFilterText, (val) => {
		dicRef.value.filter(val)
	})

	watch(visible, async (val) => {
		if (val) {
			const res = await proxy.$API.system.commPost(props.apiUrl + "/tree")({
				model: proxy.model
			})
			nowDicList.value = res.data
		}
	})

	//暴露方法给父组件
	defineExpose({
		getCurrentNode
	});
</script>

<style scoped>
	.menu:deep(.el-tree-node__label) {
		display: flex;
		flex: 1;
		height: 100%;
	}

	:deep(.el-tree.menu .el-tree-node__content) {
		min-height: 36px;
		height: auto;
	}

	.custom-tree-node {
		display: flex;
		flex: 1;
		align-items: center;
		justify-content: space-between;
		font-size: 14px;
		padding-right: 10px;
		height: 100%;
	}

	.custom-tree-node .do {
		display: none;
	}

	.custom-tree-node:hover .do {
		display: inline-block;
	}

	:deep(.el-button + .el-dropdown) {
		margin-left: 0px !important;
	}
</style>
